package com.concurrency.juc.synctools.cas;

import com.sun.org.apache.xerces.internal.xs.PSVIProvider;

public class CasDemo1 {
    public static void main(String[] args) {
        final CompareAndGet cas = new CompareAndGet();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int expectedValue = cas.get();
                int newValue = (int) (Math.random() * 100);
                boolean b = cas.compareAndSet(expectedValue, newValue);
                System.out.println(Thread.currentThread().getId()+"|"+newValue + " | " + expectedValue + " | " + b);
            }).start();
        }
    }

    static class CompareAndGet {
        private int value;

        //获取值
        public synchronized int get() {
            return value;
        }

        public synchronized int compareAndSwap(int expectedValue, int newValue) {
            //获取就的值
            int oldValue = value;

            if (oldValue == expectedValue) {
                this.value = newValue;
            }
            // 返回修改之前的值
            return oldValue;
        }

        public synchronized boolean compareAndSet(int expectedValue, int newValue) {
            return expectedValue == compareAndSwap(expectedValue, newValue);
        }

    }

}
